package com.huangmb.idea.ui;

import com.huangmb.idea.bean.BaseTask;
import com.huangmb.idea.bean.TranslateResult;
import com.huangmb.idea.utils.TaskManager;
import com.huangmb.idea.utils.TranslateUtils;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

/**
 * Created by huangmb on 2016/12/12.
 */
public class TranslateToolWindowFactory implements ToolWindowFactory,ActionListener{
    private JPanel mPanel1;
    private JTextField mInput;
    private JButton mSubmitButton;
    private JTextArea mResultArea;
    private ToolWindow mToolWindow;
    public TranslateToolWindowFactory(){
        mInput.registerKeyboardAction(this,KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true),JComponent.WHEN_FOCUSED);

        mSubmitButton.addActionListener(this);
    }
    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        mToolWindow = toolWindow;
        ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
        Content content = contentFactory.createContent(mPanel1, "", false);
        toolWindow.getContentManager().addContent(content);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String word = mInput.getText();

        if (TextUtils.isBlank(word)){
            mResultArea.setText("请输入单词");
            mInput.setText("");
            return;
        }
        TranslateUtils.query(word.trim(), new TaskManager.CallBack() {
            @Override
            public void onSuccess(BaseTask task, TranslateResult result) {
                mInput.setText("");
                mResultArea.setText(result.toString());
            }

            @Override
            public void onFailed(BaseTask task, Exception e) {
                mInput.setText("");
                mResultArea.setText("查询失败\n"+e.toString());
            }
        });
    }
}
